package cn.com.tuns.assess.qsb.frame.ui;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;
import cn.com.tuns.assess.qsb.R;
import cn.com.tuns.assess.qsb.frame.bean.LoginData;
import cn.com.tuns.assess.qsb.frame.util.DBUtil;
import cn.com.tuns.assess.qsb.frame.util.FileUtil;
import cn.com.tuns.assess.qsb.frame.util.SharedPreferencesUtil;
import com.google.gson.Gson;

import java.io.*;

public class AppManage {
    private final static String LoginDataKey="saveLoginDataKey";

    /**
     * 系统设置库
     */
    public final static String setDB = "system.db";
    /**
     * 业务库
     */
    public final static String userDB = "user.db";

    public static String userId;
    public static String realName;
    public static String nickName;
    public static String phone;
    public static boolean isLogin;

    public static String getRootPath(){
        String path=MyApplication.context.getExternalFilesDir(null).getAbsolutePath()+"/";
        return path;
    }

    public static String getSysLogPath(){
        File file=new File(getRootPath(),"log");
        if(!file.exists())
        {
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    public static String getUserPath(){
        File file=new File(getRootPath(),userId);
        if(!file.exists())
        {
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    public static String getCameraPath(){
        File file=new File(getRootPath(),"camera");
        if(!file.exists())
        {
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    /**
     * 显示提示信息
     *
     * @param msg
     */
    public static void showToastMessage(String msg) {
        try {
            Toast toast = Toast.makeText(MyApplication.context, msg, Toast.LENGTH_LONG);
            toast.show();
        } catch (Exception e) {
            //解决在子线程中调用Toast的异常情况处理
            Looper.prepare();
            Toast.makeText(MyApplication.context, msg, Toast.LENGTH_LONG).show();
            Looper.loop();
        }
    }

    public static void saveLoginData(){
        LoginData loginData=new LoginData();
        loginData.phone=phone;
        loginData.realName=realName;
        loginData.nickName=nickName;
        loginData.userId=userId;
        loginData.isLogin=isLogin;

        String json=new Gson().toJson(loginData);
        SharedPreferencesUtil.save(LoginDataKey,json);
    }

    public static void readLoginData(){
        String json=SharedPreferencesUtil.read(LoginDataKey);
        if(!TextUtils.isEmpty(json))
        {
            LoginData loginData=new Gson().fromJson(json,LoginData.class);
            if(loginData!=null) {
                phone = loginData.phone;
                realName = loginData.realName;
                nickName = loginData.nickName;
                userId = loginData.userId;
                isLogin = loginData.isLogin;
            }
        }

    }

    /**
     * 用户数据库
     */
    private static  SQLiteDatabase userDb=null;
    /** 当前用户数据库名称*/
    private static String userDbName=null;
    /** 系统数据库*/
    private static SQLiteDatabase systemDb = null;

    /**
     * 打开本地系统数据库
     *
     * @return
     */
    public synchronized static SQLiteDatabase dbSys() {
        // if (systemDb != null && systemDb.isOpen()) {
        // Log.e("db error", "system_db is open");
        // return systemDb;
        // }
        if (systemDb != null) {
            return systemDb;
        }
        System.out.println("open db...");
        try {
            File file = new File(getDbSysPathName());
            // 因为本地数据库都是COPY的，所以不能自己创建数据库
            if (!file.exists()) {
                try {
                    throw new RuntimeException("dbfile not exists");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("本地数据库出现错误。=" + file.getAbsolutePath());
                return null;
            }
            systemDb = SQLiteDatabase.openOrCreateDatabase(file, null);
        } catch (Exception e) {
            System.out.println("本地数据库出现错误。=" );
            e.printStackTrace();
        }
        return systemDb;
    }

    /**
     * 打开本地用户数据库
     *
     * @return
     */
    public synchronized static SQLiteDatabase dbUser() {
        // if (userDb != null && userDb.isOpen()) {
        // Log.e("db error", "user_db is open");
        // return userDb;
        // }
        if(userDb!=null && userDbName!=null ){
            if(AppManage.userId.equals(userDbName)) {
                return userDb;
            }else{
                userDb.close();
                userDb=null;
            }
        }
        try {
            File file = new File(getDbUserPathName());
            // 因为本地数据库都是COPY的，所以不能自己创建数据库
            if (!file.exists()) {
                return null;
            }
            userDb = SQLiteDatabase.openOrCreateDatabase(file, null);
            userDbName=userId;
            return userDb;
        } catch (Exception e) {
            System.out.println("本地数据库出现错误。=" );
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 检查本地用户数据库文件是否存在，不在从RAW文件夹中COPY
     */
    public void checkDbUser() {
        // 检查本地是否有数据库文件
        String fileName = getUserPath() + "/" + userDB;
        File file = new File(fileName);
        if (!file.exists()) {
            createFileByStream(
                    MyApplication.context.getResources().openRawResource(R.raw.user),fileName);
        }
    }

    /**
     * 检查本地用户数据库文件是否存在，不在从RAW文件夹中COPY
     */
    public static void checkDbSys() {
        // 检查本地是否有数据库文件
        String fileName = getDbSysPathName();
        File file = new File(fileName);
        if (!file.exists()) {
            createFileByStream(
                    MyApplication.context.getResources().openRawResource(R.raw.system)
                    ,fileName);
        }
    }

    /**
     * 从inStream拷贝到SD卡生成文件
     *
     * @return
     */
    public static boolean createFileByStream(InputStream inStream, String dstFileName) {
        try {
            createPathByFile(dstFileName);// 创建多级目录结构

            int len = 0;
            byte[] bytes = new byte[1024];
            FileOutputStream fos = new FileOutputStream(new File(dstFileName));
            while ((len = inStream.read(bytes, 0, 1024)) > 0) {
                fos.write(bytes, 0, len);
            }
            inStream.close();
            fos.close();
        } catch (FileNotFoundException e) {
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 根据文件建立目录
     *
     * @param fileName
     * @return
     */
    public static boolean createPathByFile(String fileName) {
        int start = fileName.lastIndexOf("/");
        if (start > 0) {
            String path = fileName.substring(0, start);
            File dstfile = new File(path);
            if (!dstfile.exists())
                dstfile.mkdirs();// 创建多级目录结构
        }
        return true;
    }


    /**
     * 得到本地系统数据库文件与路径
     */
    public static String getDbSysPathName() {
        return getRootPath() + "/" + setDB;
    }

    /**
     * 得到本地用户数据库文件与路径
     */
    public static String getDbUserPathName() {
        return getUserPath() + "/" + userDB;
    }

    /**
     * 用户数据库
     *
     * @return
     */
    public static DBUtil getDbSys() {
        DBUtil dbUtil = new DBUtil(getDbSysPathName());
        return dbUtil;
    }
    /**
     * 用户数据库
     *
     * @return
     */
    public static DBUtil getDbUser() {
        DBUtil dbUtil = new DBUtil(getDbUserPathName());
        return dbUtil;
    }

    /**
     * 关闭所有数据库
     */
    public static void closeAllDB(){
        try {
            if (systemDb != null) {
                systemDb.close();
                systemDb = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            if (userDb != null) {
                userDb.close();
                userDb = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 关闭用户数据库
     */
    public static void closeUseDB() {
        try {
            if (userDb != null) {
                userDb.close();
                userDb = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测数据库版本(注意处理后，数据库不会自动关闭)
     *
     * @param dbFile
     *            数据库路径名称与文件名称
     * @param dbName
     *            要升级的数据库(LocalDBPatch.USER_DB或LocalDBPatch.SYSTEM_DB)
     * @return
     */
    public static boolean checkDBVersion(String dbFile, String dbName) {
        String[] dbConfig = null;
        try {
            String[] dbConfigs = MyApplication.context.getResources()
                    .getStringArray(R.array.dbConfigs);
            for (String config : dbConfigs) {
                String[] entity = config.split(",");
                if (dbName.equals(entity[1])) {
                    dbConfig = entity;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if (dbConfig == null) {
            // 没有找到要更新数据的的配置信息
            return false;
        }
        String fileName = dbConfig[0];
        // 获取当前版本号
        int dbVersion = Integer.valueOf(dbConfig[6]);
        DBUtil db = new DBUtil(dbFile);
        // System.out.println("update db[[dbversion=" + dbVersion
        // + "=checkDBVersion==" + dbFile);
        try {
            db.openDB();

            String table = dbConfig[2];
            String keyField = dbConfig[3];
            String keyValue = dbConfig[4];
            String outField = dbConfig[5];
            // 1检测数据库版本
            String dbVer = db.getByKeyString(table, keyField, keyValue,
                    outField);
            if (TextUtils.isEmpty(dbVer))
                dbVer = "1";

            int ver = Integer.valueOf(dbVer);
            if (ver >= dbVersion)
                return true;
            ver++;// 从下一个版本开始更新
            // 更新本地数据库结构
            db.beginTransaction();
            for (int i = ver; i <= dbVersion; i++) {
                int resId = MyApplication.context.getResources().getIdentifier(
                        fileName + i, "raw", getPackageName());
                System.out.println("执行数据库补丁:" + dbName + "=version:" + i);
                runSqlPatch(db, resId, MyApplication.context);
            }
            // 记录最新版本
            db.updateColByKey(table, keyField, keyValue, outField,
                    String.valueOf(dbVersion));
            db.endTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.close();
        }
        return true;
    }

    /**
     * 逐行运行资源文件里的sql语句
     *
     * @param resID
     * @return
     */
    private static boolean runSqlPatch(DBUtil db, int resID, Context context) {
        String sqls = FileUtil.getContentFromStream(context.getResources()
                .openRawResource(resID), "utf-8");
        if (sqls == null || sqls.length() == 0)
            return true;
        String[] sqlArray = sqls.split("\n");
        if (sqlArray.length > 0) {
            int st = 0;
            for (int i = st; i < sqlArray.length; i++) {
                if (sqlArray[i] != null && sqlArray[i].length() > 0) {
                    // System.out.println("执行数据库补丁:" + sqlArray[i]);
                    db.execSQL(sqlArray[i], null);
                }
            }
        }
        return true;
    }



    /**
     * 程序包名中最后一个单词 如:com.unisoft.ptl则返回ptl
     *
     * @return
     */
    public static String getPackageLastName() {
        String pkgName = getPackageName();
        return pkgName.substring(pkgName.lastIndexOf(".") + 1);
    }

    /**
     * 程序包名
     *
     * @return
     */
    public static String getPackageName() {
        try {

            PackageManager packageManager = MyApplication.context.getPackageManager();

            PackageInfo packageInfo = packageManager.getPackageInfo(

                    MyApplication.context.getPackageName(), 0);

            return packageInfo.packageName;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return "";

    }



}
